package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.enums.AuditStatus;
import com.yami.shop.bean.model.ShopAuditing;
import com.yami.shop.bean.model.ShopCompany;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.dao.ShopAuditingMapper;
import com.yami.shop.dao.ShopCompanyMapper;
import com.yami.shop.service.ShopCompanyService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author lth
 * @Date 2021/8/3 16:16
 */
@Service
@AllArgsConstructor
public class ShopCompanyServiceImpl extends ServiceImpl<ShopCompanyMapper, ShopCompany> implements ShopCompanyService {

    private final ShopCompanyMapper shopCompanyMapper;
    private final ShopAuditingMapper shopAuditingMapper;

    @Override
    public void saveInfo(ShopCompany shopCompany) {
        this.checkInfo(shopCompany);
        save(shopCompany);
    }

    @Override
    public void updateByShopId(ShopCompany shopCompany) {
        this.checkInfo(shopCompany);
        saveOrUpdate(shopCompany, Wrappers.lambdaUpdate(ShopCompany.class).eq(ShopCompany::getShopId, shopCompany.getShopId()).eq(ShopCompany::getStatus, shopCompany.getStatus()));
    }

    /**
     * 校验店铺工商信息
     * @param shopCompany
     */
    private void checkInfo(ShopCompany shopCompany) {
        ShopCompany creditCodeObj = shopCompanyMapper.selectOne(Wrappers.lambdaQuery(ShopCompany.class)
                                    .eq(ShopCompany::getCreditCode, shopCompany.getCreditCode()).eq(ShopCompany::getStatus, AuditStatus.SUCCESSAUDIT.value()));
        if (Objects.nonNull(creditCodeObj) && !Objects.equals(shopCompany.getShopId(), creditCodeObj.getShopId())) {
            throw new YamiShopBindException("yami.shop.company.credit.code.repeat");
        }
        if (Objects.isNull(shopCompany.getStartTime())) {
            throw new YamiShopBindException("yami.shop.company.date.not.empty");
        }
        if (!Objects.isNull(shopCompany.getEndTime()) && !shopCompany.getStartTime().before(shopCompany.getEndTime())) {
            throw new YamiShopBindException("yami.shop.business.date.error");
        }
        long count = shopAuditingMapper.selectCount(Wrappers.lambdaQuery(ShopAuditing.class)
                .eq(ShopAuditing::getShopId, shopCompany.getShopId())
                .eq(ShopAuditing::getStatus, 0)
        );
        if(count != 0){
            throw new YamiShopBindException("yami.product.shop.AUDIT");
        }
    }
}
